package com.katze.common.zip;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryRequest;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntryRequestSupplier;
import org.apache.commons.io.input.NullInputStream;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.ZipEntry;

public class ZipArchiveRequest implements ZipArchiveEntryRequestSupplier {

    private final Path source;

    private final ZipArchiveEntry entry;


    public ZipArchiveRequest(Path source, Path name) {
        this(source, name.toString());
    }

    public ZipArchiveRequest(Path source, String name) {
        this.source = source;
        this.entry = new ZipArchiveEntry(source.toFile(), name);
        this.entry.setMethod(ZipEntry.DEFLATED);
    }


    @Override
    public ZipArchiveEntryRequest get() {
        return ZipArchiveEntryRequest.createZipArchiveEntryRequest(entry,  () -> {
            try {
                return isDirectory()? new NullInputStream(0):Files.newInputStream(source);
            } catch (IOException e) {
                throw new RuntimeException(source + " 文件加载失败", e);
            }
        });
    }

    public boolean isDirectory() {
        return entry.isDirectory();
    }

    public boolean isUnixSymlink() {
        return entry.isUnixSymlink();
    }
}
